﻿using UnityEngine;

public class Bullet : MonoBehaviour {

    public SpriteRenderer spriteRenderer;
    public Vector2 velocity;
    public float LifeTime;

    private Rigidbody2D rgb2D;
    private BulletPool pool;
    private float lifeTime;
    private bool direction;

    public void Start()
    {
        rgb2D = GetComponent<Rigidbody2D>();
    }

    public void FixedUpdate()
    {
        lifeTime += Time.deltaTime;
        
        Vector2 deltaPosition = velocity * Time.deltaTime * (direction ? 1 : -1);
        rgb2D.position = rgb2D.position + deltaPosition;

        if (lifeTime >= LifeTime)
            pool.Restore(this);
    }

    public void OnTriggerEnter2D(Collider2D collision)
    {
        if(collision.tag == "Chest")
        {
            Chest chest = collision.GetComponent<Chest>();
            chest.Explosion();
            pool.Restore(this);
        }
        else if(collision.tag == "Platform")
        {
            pool.Restore(this);
        }
    }

    public void SetPool(BulletPool bulletPool)
    {
        pool = bulletPool;
    }

    public void Fire(bool direction)
    {
        this.direction = direction;
        spriteRenderer.flipX = !this.direction;
        lifeTime = 0f;
        gameObject.SetActive(true);
    }

    public void Restore()
    {
        gameObject.SetActive(false);
    }    
}
